import { formatContent } from 'nginx-config-formatter';

export interface ValidationResult {
    isValid: boolean;
    message?: string;
}

export const formatNginxConfig = async (config: string): Promise<string> => {
    try {
        if (!config.trim()) {
            throw new Error('配置内容不能为空');
        }

        const formatted = formatContent(config, {
            indentStyle: 'space',
            dontJoinCurlyBracket: false,
            align: true,
            trailingBlankLines: true,
            extension: 'conf'
        });

        return formatted;
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '格式化失败';
        throw new Error(`格式化失败: ${errorMessage}`);
    }
};

export const validateNginxConfig = (config: string): ValidationResult => {
    try {
        if (!config.trim()) {
            return {
                isValid: false,
                message: '配置内容不能为空'
            };
        }

        // 基础语法检查
        const basicChecks = [
            {
                pattern: /^\s*server\s*\{/m,
                message: '缺少 server 块'
            },
            {
                pattern: /^\s*location\s+/m,
                message: '缺少 location 指令'
            },
            {
                pattern: /^\s*listen\s+/m,
                message: '缺少 listen 指令'
            }
        ];

        // 检查大括号匹配
        const openBraces = (config.match(/\{/g) || []).length;
        const closeBraces = (config.match(/\}/g) || []).length;
        
        if (openBraces !== closeBraces) {
            return {
                isValid: false,
                message: `大括号不匹配: 开始括号 ${openBraces} 个，结束括号 ${closeBraces} 个`
            };
        }

        // 检查分号
        const lines = config.split('\n');
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line && !line.endsWith(';') && !line.endsWith('{') && !line.endsWith('}') && !line.startsWith('#')) {
                // 跳过空行和注释
                if (!/^\s*$/.test(line)) {
                    return {
                        isValid: false,
                        message: `第 ${i + 1} 行缺少分号: ${line}`
                    };
                }
            }
        }

        // 基础结构检查
        for (const check of basicChecks) {
            if (!check.pattern.test(config)) {
                return {
                    isValid: false,
                    message: check.message
                };
            }
        }

        return {
            isValid: true,
            message: '配置语法正确'
        };
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '验证失败';
        return {
            isValid: false,
            message: `验证失败: ${errorMessage}`
        };
    }
}; 